import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dartz/dartz.dart';

import '../core/api_result.dart';
import '../core/base_repository.dart';
import '../core/http_client.dart';
import '../../models/tunnel_models.dart';

/// 隧道Repository
class TunnelRepository extends BaseRepository {
  TunnelRepository(super.httpClient);

  /// 创建隧道
  Future<ApiResult<CreateTunnelResponse>> createTunnel({
    required String localHost,
    required String localPort,
    required String serverName,
    String tunnelType = 'http',
  }) async {
    final request = CreateTunnelRequest(
      localHost: localHost,
      localPort: localPort,
      serverName: serverName,
      tunnelType: tunnelType,
    );
    return post<CreateTunnelResponse>(
      '/create/tunnel',
      data: request.toJson(),
      fromJson: CreateTunnelResponse.fromJson,
    );
  }

  /// 获取隧道列表
  Future<ApiResult<List<TunnelData>>> getTunnels() async {
    final result = await get<Map<String, dynamic>>('/tunnels', fromJson: (json) => json);
    
    return result.fold(
      (failure) => Left(failure),
      (data) {
        try {
          final tunnelsData = data['tunnels'] as List<dynamic>?;
          if (tunnelsData == null) {
            return const Right([]);
          }
          final tunnels = tunnelsData
              .map((item) => TunnelData.fromJson(item as Map<String, dynamic>))
              .toList();
          return Right(tunnels);
        } catch (e) {
          return Left(ServerFailure('解析隧道列表失败: $e'));
        }
      },
    );
  }

  /// 获取单个隧道详情
  Future<ApiResult<TunnelData>> getTunnel(String tunnelId) async {
    return get<TunnelData>(
      '/tunnels/$tunnelId',
      fromJson: TunnelData.fromJson,
    );
  }

  /// 删除隧道
  Future<ApiResult<void>> deleteTunnel(String tunnelId) async {
    return delete<void>('/tunnels/$tunnelId');
  }

  /// 更新隧道
  Future<ApiResult<CreateTunnelResponse>> updateTunnel({
    required String tunnelId,
    required String localHost,
    required String localPort,
    required String serverName,
    String tunnelType = 'http',
  }) async {
    final request = CreateTunnelRequest(
      localHost: localHost,
      localPort: localPort,
      serverName: serverName,
      tunnelType: tunnelType,
    );
    return put<CreateTunnelResponse>(
      '/tunnels/$tunnelId',
      data: request.toJson(),
      fromJson: CreateTunnelResponse.fromJson,
    );
  }

  /// 更新隧道连接状态
  Future<ApiResult<Map<String, dynamic>>> updateTunnelStatus({
    required String tunnelId,
    required String status, // 'active', 'inactive', 'connecting', 'disconnected', 'error'
    String? errorMessage,
  }) async {
    final Map<String, dynamic> data = {
      'status': status,
    };
    if (errorMessage != null) {
      data['error_message'] = errorMessage;
    }

    return patch<Map<String, dynamic>>(
      '/tunnels/$tunnelId/status',
      data: data,
      fromJson: (json) => json as Map<String, dynamic>,
    );
  }
}

/// TunnelRepository Provider - 使用响应式HTTP客户端
final tunnelRepositoryProvider = Provider<TunnelRepository>(
  (ref) => TunnelRepository(ref.watch(reactiveHttpClientProvider)),
);

